package controllers;

import play.*;
import play.data.validation.Required;
import play.mvc.*;
import utils.ApplicationMessages;
import Enums.PlaceTypeEnums;
import common.FBSecure;
import common.FBUtil;

import java.util.*;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import models.*;

@With(FBSecure.class)
public class Application extends FBController {

    public static void index() {
      User currentUser = getUser();
      
    	String oauthToken = getOAuthToken();
    
    	String facebookName = null;
    	JsonElement je;
    
    	  je = FBUtil.getInstance().executeGraphRequest("/"+currentUser.getFacebookID()+"?fields=name,id,picture", oauthToken);
    	  facebookName = je.getAsJsonObject().get("name").getAsString();
   	      String pictureUrl = je.getAsJsonObject().get("picture").getAsString();
    	  currentUser.setFacebookPictureUrl(pictureUrl);
    	  currentUser.setFacebookName(facebookName);
    	  currentUser.save();
    	  String facebookApplicationID = Play.configuration.getProperty("fb.app.id"); 
          render(facebookApplicationID, facebookName,currentUser);
    }
    
    public static void cities(){
    	User currentUser = getUser();
    	String facebookApplicationID = Play.configuration.getProperty("fb.app.id");
    	List<UserCity> userCities = currentUser.getCities();
    	render(facebookApplicationID,currentUser.getFacebookName(),currentUser,userCities);
    }
   
    public static void addCityUser(String  userRequest){
      JsonObject userRequestJson = (JsonObject) new JsonParser().parse(userRequest);
      
      long userId = userRequestJson.get("userId").getAsLong();
      int cityType = userRequestJson.get("cityType").getAsInt();
      JsonObject cityCordinate = userRequestJson.get("selectedCity").getAsJsonObject();
      double lat = cityCordinate.get("latitude").getAsDouble();
      double lng = cityCordinate.get("longitute").getAsDouble();
      String cityName = cityCordinate.get("cityName").getAsString();
      User currentUser = getUser();
      UserCity newUserCity = UserCity.findOrCreateCity(lat, lng, cityName,cityType,currentUser);
      PlaceTypeEnums placeTypes = PlaceTypeEnums.convertValueToEnum(cityType);
     
      if(newUserCity.getUserId() < 0){
    	  
    	  PlaceInfo placeInfo = PlaceInfo.findOrCreatePlaceInfo(lat, lng, cityName);
    	  if(placeInfo.getId() != null){
    		  newUserCity.setPlaceInfoId(placeInfo.getId());
    		  newUserCity.saveUserCity(newUserCity, new UserCityType(placeTypes.getValue(), placeTypes.getDesc()));
    	  }else{ 
    	     Cordinate newCordinate = new Cordinate(lat, lng);
    	     UserCityType userCityType =  new UserCityType(placeTypes.getValue(),placeTypes.getDesc());
    	     newUserCity = newUserCity.saveUserCity(newUserCity, placeInfo, newCordinate, userCityType);
    	  }
      }else{
    	 newUserCity.saveUserCity(newUserCity, new UserCityType(placeTypes.getValue(), placeTypes.getDesc()));
      }
      
 
      
      UserCity addedCity = currentUser.addCityOfUser(newUserCity);
      ApplicationMessages message = new ApplicationMessages();
      JsonObject responseMessage = message.createAddCityUserSuccessMessage(addedCity,currentUser);
      renderJSON(responseMessage.toString());
      
      
    }
    
    public static void afterAddPlace(long cityId){
    	User currentUser = getUser();
    	UserCity userCity  = UserCity.findById(cityId);
    	List<UserPlace> places=userCity.getAllUserPlaceOfThisCity();
    	String facebookApplicationID = Play.configuration.getProperty("fb.app.id");
    	render(facebookApplicationID,currentUser.getFacebookName(),currentUser,places,cityId);	
        
    }
    public static void addPlaceToCity(){
    	
    	String userRequestForPlace = params.get("requestData"); 
    	JsonObject userRequestJsonForPlace = (JsonObject)new JsonParser().parse(userRequestForPlace);
    	String searchType=userRequestJsonForPlace.get("searchType").getAsString();
    	if(searchType.contains("gmap")){
    	
    		long placeCityId=userRequestJsonForPlace.get("placeCityId").getAsLong();
    		int placeType=userRequestJsonForPlace.get("placeType").getAsInt();
    		JsonObject coordinate=userRequestJsonForPlace.get("placeCity").getAsJsonObject();
    		double lat=coordinate.get("latitude").getAsDouble();
    		double lng=coordinate.get("longitute").getAsDouble();
    		String placeName=coordinate.get("placeName").getAsString();
    	    PlaceTypeEnums placeTypes = PlaceTypeEnums.convertValueToEnum(placeType);
    		UserCity userCity=UserCity.findById(placeCityId);
    		UserPlace userPlace=UserPlace.findOrCreatePlace(lat, lng, placeName);
    		if(userPlace.getId()!=null){
    			ApplicationMessages message = new ApplicationMessages();
    		    JsonObject responseMessage = message.userHasAlreadyPlaceMessage(userPlace, userCity);
    		    renderJSON(responseMessage.toString());
    		}
    		else{
    			PlaceInfo placeInfo=PlaceInfo.findOrCreatePlaceInfo(lat, lng, placeName);
    			if(placeInfo.getId()!=null){
    				UserPlace newUserPlace=new UserPlace(placeName);
    				newUserPlace.setPlaceInfoId(placeInfo.getId());
    				UserPlaceType userPlaceType=new UserPlaceType(placeType, placeTypes.getDesc());
    				newUserPlace.saveUserPlace(newUserPlace, userPlaceType);
    				userCity.addUserPlace(newUserPlace);
    			}
    			else{
    				Cordinate cordinate=new Cordinate(lat, lng);
    				PlaceInfo newPlaceInfo=new PlaceInfo(placeName);
    				UserPlaceType userPlaceType=new UserPlaceType(placeType, placeTypes.getDesc());
    				UserPlace newUserPlace=new UserPlace(placeName);
    				newUserPlace.saveUserPlace(newUserPlace, newPlaceInfo, cordinate, userPlaceType);
    				userCity.addUserPlace(newUserPlace);
    				
    			}
    			ApplicationMessages message = new ApplicationMessages();
    		    JsonObject responseMessage = message.addUserPlaceSuccesfullMessage(userPlace, userCity);
    		    renderJSON(responseMessage.toString());
    		}
    	    
    	}
    	else {
    		long placeId=userRequestJsonForPlace.get("placeId").getAsLong();
    		long placeCityId=userRequestJsonForPlace.get("placeCityId").getAsLong();
    		int placeType=userRequestJsonForPlace.get("placeType").getAsInt();
    		Cordinate coordinate=Cordinate.findById(placeId);
    		double lat=coordinate.getLatitude();
    		double lng=coordinate.getLongitude();
    		UserPlace selectedPlace = UserPlace.findById(placeId);
    		PlaceInfo placeInfo = selectedPlace.getPlaceInfo();
    		String placeName=placeInfo.getFormatted_placeName();
    	    PlaceTypeEnums placeTypes = PlaceTypeEnums.convertValueToEnum(placeType);
    	    User currentUser=getUser();
    	    User selectedPlaceUser=selectedPlace.getCity().getUser();
    	    UserPlace newUserPlace=null;
    	    UserCity userCity=null;
    	    if(currentUser.getId().longValue()!=selectedPlaceUser.getId().longValue()){
    	    newUserPlace = new UserPlace(placeName);
    	    newUserPlace.setPlaceInfoId(placeInfo.getId());
    	    
    	    userCity=UserCity.findById(placeCityId);
    	    newUserPlace.saveUserPlace(newUserPlace, new UserPlaceType(placeTypes.getValue(), placeTypes.getDesc()));
    	    userCity.addUserPlace(newUserPlace);
    	    ApplicationMessages message = new ApplicationMessages();
		    JsonObject responseMessage = message.addUserPlaceSuccesfullMessage(newUserPlace, userCity);
		    renderJSON(responseMessage.toString());
    	    }
    	    else{
    	    	ApplicationMessages message = new ApplicationMessages();
    	        JsonObject responseMessage = message.userHasAlreadyPlaceMessage(newUserPlace, userCity);
    	        renderJSON(responseMessage.toString());
    	        
    	    }
    	}
    	
    	
    }
    
    public static void getUserPlaceOfUserCity(long userCityId){
    	UserCity userCity = UserCity.findById(userCityId);
    	if(userCity == null ){
    		// error messageGondee
    		return;
    	}
    	List<UserPlace> userPlaces = userCity.getUserCityPlaces();
    	ApplicationMessages  message = new ApplicationMessages();
    	JsonObject responseMessage = message.creategeUserPlaceOfCityMessage(userPlaces);
    	renderJSON(responseMessage.toString());
    }
}
